﻿
#include "RootWindow.h"
#include "FirstViewController.h"
#include "DesignViewController.h"

static RootWindow* _window = NULL;
static int flag = 0;
struct cc_timeval now;

RootWindow* RootWindow::getInstance()
{
	if (NULL == _window)
	{
		_window = new RootWindow();
		_window->init();
		_window->autorelease();
	}
	return _window;
}

RootWindow::RootWindow()
:m_pRootNavigationController(NULL)
{
	CAApplication::getApplication()->getKeypadDispatcher()->addDelegate(this);
}

RootWindow::~RootWindow()
{
	CAApplication::getApplication()->getKeypadDispatcher()->removeDelegate(this);
}

bool RootWindow::init()
{
    if (!CAWindow::init())
    {
        return false;
    }
	FirstViewController* firstController = new FirstViewController();
	firstController->init();
	if (m_pRootNavigationController)
	{
		m_pRootNavigationController->replaceViewController(firstController, false);
	}
	else
	{
		//创建Navigation
		m_pRootNavigationController = new CANavigationController();
		m_pRootNavigationController->setNavigationBarBackgroundImage(CAImage::create("source_pro/up_navigationbar.png"));
	}

	//隐藏掉firstController导航栏
	CANavigationBarItem* nItem = CANavigationBarItem::create("");
	nItem->setNagigationBarHidden(true);
	firstController->setNavigationBarItem(nItem);

	//使用一个firstController初始化Navigation
	m_pRootNavigationController->initWithRootViewController(firstController);
	this->setRootViewController(m_pRootNavigationController);

	firstController->release();
	m_pRootNavigationController->release();

	return true;
}

void RootWindow::keyBackClicked()
{
	CC_RETURN_IF(CAAlertView::hideWithDisplayed());
	if (this->getModalViewController())
	{
		this->dismissModalViewController(true);
	}
	else if(this->getRootNavigationController()->getViewControllerCount() > 1)
	{
		this->getRootNavigationController()->popViewControllerAnimated(true);
	}
	else
	{
		CAAlertView* alertView = CAAlertView::createWithText(UTF8("提示"), UTF8("您确定要退出程序吗？"), UTF8("确定"), UTF8("取消"),NULL);
		alertView->show();
		alertView->setTarget(this, CAAlertView_selector(RootWindow::alertCallBack));
	}
}

void RootWindow::alertCallBack(int btnIndex)
{
	if (0 == btnIndex)
	{
		CAApplication::getApplication()->end();
	}
}
